import wx from 'wx'
import Fly from 'flyio'
import { config, JSONo } from './config'
// import { getStorage, setStorage } from '@/utils/wechat'

const request = new Fly()

request.config.timeout = 10 * 1000

if (process.env.METHOD === 'proxy1') {
  request.config.baseURL = 'http://localhost:3001/api2' // 本地代理1(100次/小时)
} else if (process.env.METHOD === 'proxy2') {
  request.config.baseURL = 'http://localhost:3002' // 本地代理2(100次/小时)
} else {
  request.config.baseURL = config.api
}

request.interceptors.request.use((request) => {
  // wx.showLoading({ title: '加载中...' })
  request.body = JSONo(request.body, {
    appletId: config.id
  })
  try {
    let res = wx.getStorageSync('accessToken')
    const { token, expires } = res
    // 有缓存，判断是否过期
    if (token && expires > Date.now()) {
      request.headers = JSONo(request.headers, {
        accessToken: token
      })
    } else {
      // wx.clearStorageSync()
      // console.log(request)
      // console.log('已经过期')
    }
  } catch (error) {
    // console.log(error)
    // wx.clearStorageSync()
    console.log('已经过期')
  }
  return request
})

request.interceptors.response.use(
  (response, promise) => {
    // wx.hideLoading()
    console.log(response)
    if (response.status !== 200) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '服务器异常:' + response.status
      })
      wx.hideLoading()
    }
    return promise.resolve(response.data)
  },
  (err, promise) => {
    // wx.hideLoading()
    // wx.showToast({
    //   title: err.message,
    //   icon: 'none'
    // })
    console.log(err)
    if (err.status === 401) {
      wx.removeStorage({
        key: 'accessToken',
        success: () => {
          console.log('clear')
        }
      })
      // wx.navigateTo({ url: '/pages/index/main' })
    } else {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '服务器异常:' + err.status
      })
      wx.hideLoading()
    }

    return promise.resolve()
  }
)

export default request
